import _ from 'lodash'
import File from '@/editor/common/js/workspace/file'
import { edgeReadPathSeparator, edgeReadFile, edgeDesignView, edgeListSiddhiApps, edgeRunApp, edgeStopApp } from '@/api/siddhi';
import { edgeDesignDiagram } from '@/api/project'
import { base64EncodeUnicode, base64DecodeUnicode } from '@/utils/utils';
import store from '@/store'
export default class ServiceClient {

  constructor(args) {
    this.application = _.get(args, 'application');
  }

  getErrorFromResponse = function (xhr, textStatus, errorThrown) {
    var msg = _.isString(errorThrown) ? errorThrown : xhr.statusText,
      responseObj;
    try {
      responseObj = JSON.parse(xhr.responseText);
    } catch (e) {
      // ignore
    }
    if (!_.isNil(responseObj)) {
      if (_.has(responseObj, 'Error')) {
        msg = _.get(responseObj, 'Error');
      }
    }
    return { "error": true, "message": msg };
  };

  /**
   * parser source
   * @param ServiceClient
   */
  parse = function (source) {
    var content = { "content": source };
    var data = {};
    $.ajax({
      type: "POST",
      context: this,
      url: _.get(this.application, 'config.services.parser.endpoint'),
      data: JSON.stringify(content),
      contentType: "application/json; charset=utf-8",
      async: false,
      dataType: "json",
      success: function (response) {
        data = response;
      },
      error: function (xhr, textStatus, errorThrown) {
        data = getErrorFromResponse(xhr, textStatus, errorThrown);
        log.error(data.message);
      }
    });
    return data;
  };

  /**
   * validate source
   * @param String source
   */
  validate = function (source) {
    var content = { "content": source };
    var data = {};
    $.ajax({
      type: "POST",
      context: this,
      url: _.get(this.application, 'config.services.validator.endpoint'),
      data: JSON.stringify(content),
      contentType: "application/json; charset=utf-8",
      async: false,
      dataType: "json",
      success: function (response) {
        data = response;
      },
      error: function (xhr, textStatus, errorThrown) {
        data = getErrorFromResponse(xhr, textStatus, errorThrown);
        log.error(data.message);
      }
    });
    return data;
  };

  /**
   * read content of a file
   * @param {String} filePath file path
   */
  async readFileContent(filePath) {
    var data = {};
    await edgeReadFile(filePath).then(res => {
      data = res.data;
    }).catch(Error => {
      if (Error.response != undefined) {
        store.dispatch('siddhi/setLogData', { message: Error.response.data, type: 'ERROR' })
        store.dispatch('siddhi/setConsoleState', true)
      }
    })
    return data;
  };

  readFile = async function (filePath) {
    let fileData = await this.readFileContent(filePath);
    let pathArray = _.split(filePath, this.application.getPathSeperator());
    let fileName = _.last(pathArray);
    let folderPath = _.join(_.take(pathArray, pathArray.length - 1), this.application.getPathSeperator());
    let fileObj = {
      name: fileName,
      path: folderPath,
      content: fileData.content,
      isPersisted: true,
      isDirty: false
    }
    return new File(fileObj);
  };

  exists = function (path) {
    var data = {};

    $.ajax({
      type: "GET",
      context: this,
      url: _.get(this.application, 'config.services.workspace.endpoint') + "/exists?" + "path=" +
        this.application.utils.base64EncodeUnicode(path),
      contentType: "text/plain; charset=utf-8",
      async: false,
      success: function (response) {
        data = response;
      },
      error: function (xhr, textStatus, errorThrown) {
        data = getErrorFromResponse(xhr, textStatus, errorThrown);
        log.error(data.message);
      }
    });
    return data;
  };

  readPathSeparator = function () {
    var data = {};
    edgeReadPathSeparator().then(res => {
      data = res;
    }).catch(Error => {
      console.log(Error)
    })
    return data.fileSeparator == undefined ? '/' : data.fileSeparator;
  };

  create = function (path, type) {
    var data = {};
    $.ajax({
      type: "GET",
      context: this,
      url: _.get(this.application, 'config.services.workspace.endpoint') + "/create?" + "path=" +
        this.application.utils.base64EncodeUnicode(path)
        + "&type=" + this.application.utils.base64EncodeUnicode(type),
      contentType: "text/plain; charset=utf-8",
      async: false,
      success: function (response) {
        data = response;
      },
      error: function (xhr, textStatus, errorThrown) {
        data = getErrorFromResponse(xhr, textStatus, errorThrown);
        log.error(data.message);
      }
    });
    return data;
  };

  delete = function (path, type) {
    var data = {};
    $.ajax({
      type: "GET",
      context: this,
      url: _.get(this.application, 'config.services.workspace.endpoint') + "/delete?" + "path=" +
        this.application.utils.base64EncodeUnicode(path)
        + "&type=" + this.application.utils.base64EncodeUnicode(type),
      contentType: "text/plain; charset=utf-8",
      async: false,
      success: function (response) {
        data = response;
      },
      error: function (xhr, textStatus, errorThrown) {
        data = getErrorFromResponse(xhr, textStatus, errorThrown);
        log.error(data.message);
      }
    });
    return data;
  };

  writeFile = function (file, content) {
    var self = this;
    var data = {};
    $.ajax({
      type: "POST",
      context: this,
      url: _.get(this.application, 'config.services.workspace.endpoint') + "/write",
      data: "location=" + this.application.utils.base64EncodeUnicode(file.getPath()) + "&configName=" +
        this.application.utils.base64EncodeUnicode(file.getName()) + "&config=" +
        this.application.utils.base64EncodeUnicode(content),
      contentType: "text/plain; charset=utf-8",
      async: false,
      success: function (response) {
        data = response;
        file.setDirty(false)
          .setLastPersisted(_.now())
          .save(true);
        log.debug("File " + file.getName() + ' saved successfully at ' + file.getPath());
      },
      error: function (xhr, textStatus, errorThrown) {
        data = getErrorFromResponse(xhr, textStatus, errorThrown);
        log.error(data.message);
      }
    });
    return data;
  }
  /**
   * read content of a file
   * @param {String} filePath file path
   */
  async getDesignMXContent(code) {
    let siddhiContentJson = ''
    if (code != undefined) {
      let code64 = base64EncodeUnicode(code)
      await edgeDesignView(code64).then(res => {
        siddhiContentJson = res.data;
      })
        .catch(Error => {
          console.table(Error)
          if (Error.response != undefined) {
            store.dispatch('siddhi/setLogData', { message: Error.response.data, type: 'ERROR' })
            store.dispatch('siddhi/setConsoleState', true)
          }
        })
    }
    return siddhiContentJson;
  };

  /**
   * read mxgraph 展示xml
   * @param {String} filePath file path
   */
  async getDesignMXView(json) {
    let mxgraphView = ''
    await edgeDesignDiagram(JSON.stringify(json)).then(resp => {
      if (resp.status == 200) {
        mxgraphView = resp.data.data;
      }
    })
      .catch(Error => {
        if (Error.response != undefined) {
          store.dispatch('siddhi/setLogData', { message: Error.response.data, type: 'ERROR' })
          store.dispatch('siddhi/setConsoleState', true)
        }
      })
    return mxgraphView;
  };

  /*工作空间数据加载*/
  async loadWorkspaceTree() {
    let treeList = []
    await edgeListSiddhiApps({
      // envVar: 'e30='
      path: base64EncodeUnicode('workspace'),
      id: '#'
    }).then(res => {
      if (res.status == 200) {
        let item = { mode: '0', siddhiAppName: '工作空间' }
        res.data = res.data.map(item2 => {
          return {
            ...item2,
            siddhiAppName: item2.text.indexOf('.siddhi') != -1 && _.replace(item2.text, '.siddhi', ''),
            mode: item2.type
          }
        })
        let temp1 = JSON.stringify(res.data)
        treeList.push(Object.assign(item, { 'children': JSON.parse(temp1) }))
      }
    }).catch(Error => {
      if (Error.response != undefined) {
        store.dispatch('siddhi/setLogData', { message: Error.response.data, type: 'ERROR' })
        store.dispatch('siddhi/setConsoleState', true)
      }
    })
    return treeList
  }
  /*app文件启动*/
  async runWorkspaceAPP(json) {
    await edgeRunApp(JSON.stringify(json)).then(res => {
      if (res.status == 200) {
        let resName = res.data.runtimeId;
        store.dispatch('siddhi/setLogData', { message: resName + ' 启动成功!', type: 'INFO' })
        store.dispatch('siddhi/setConsoleState', true)
      }
    }).catch(Error => {
      if (Error.response != undefined) {
        // store.dispatch('siddhi/setLogData', { message: Error.response.data, type: 'ERROR' })
        store.dispatch('siddhi/setConsoleState', true)
      }
    })
  }

  /*app文件停止*/
  async stopWorkspaceAPP(fileName) {
    await edgeStopApp(fileName).then(res => {
      if (res.status == 200) {
        store.dispatch('siddhi/setLogData', { message: fileName + ' 停止成功!', type: 'INFO' })
        store.dispatch('siddhi/setConsoleState', true)
      }
    }).catch(Error => {
      if (Error.response != undefined) {
        // store.dispatch('siddhi/setLogData', { message: Error.response.data, type: 'ERROR' })
        store.dispatch('siddhi/setConsoleState', true)
      }
    })
  }
}
